package com.twang.stock.service.jinyan;

import com.twang.stock.entity.ZhangTingBan;
import com.twang.stock.mapper.CompanyStockMinutesMapper;
import com.twang.stock.mapper.HolidayMapper;
import com.twang.stock.task.QueryZhangDieTingTask;
import com.twang.stock.service.ZhangTingBanTaskService;
import com.twang.stock.utils.date.DateUtils;
import com.twang.stock.utils.date.HolidayCopy;
import com.twang.stock.redis.RedisUtil;
import com.jayway.jsonpath.JsonPath;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class HolidayService {

    @Resource
    private HolidayMapper holidayMapper;
    @Resource
    private CompanyStockMinutesMapper companyStockMinutesMapper;
    @Autowired
    private RedisUtil redisUtil;
    //
    public static String key = "_" + "trade_status";


    /**
     *  TRUE-是工作日
     *  FALSE-不是工作日
     * @return
     */
    public  Boolean isWorkDay(String date) {
//        Holiday holiday = new Holiday();
//        holiday.setDate(date);
//        List<Holiday> holidayList = holidayMapper.select(holiday);
        //如果今天有
        Boolean keyValue = (null == redisUtil.get(HolidayCopy.getRealToday() + key)) ? Boolean.FALSE : Boolean.TRUE;
        if (keyValue) {
            System.out.println("工作日，value=" + keyValue);
            return Boolean.TRUE;
        } else {
            String tradeStatus = getTradeSattus();
            if (!"2".equals(tradeStatus)) {
                System.out.println("非交易时间：" + getTradeStatusName(Integer.valueOf(tradeStatus)));
                return Boolean.FALSE;
            }
            //
            if (null == redisUtil.get(HolidayCopy.getRealToday() + key)) {
                redisUtil.set(HolidayCopy.getRealToday() + key, tradeStatus);
                return Boolean.TRUE;
            }
            return Boolean.FALSE;
        }
    }

    /**
     * 判斷交易時間
     *  TRUE-是
     *  FALSE-不是
     * @return
     */
    public   Boolean isWorkDayTradeTime() {
        //非交易时间段
        if (DateUtils.JudgeTime("09:29:00", "11:33:00") || DateUtils.JudgeTime("12:59:00", "15:03:00")) {
            String tradeStatus = getTradeSattus();
            if (!"2".equals(tradeStatus)) {
                System.out.println("非交易时间：" + getTradeStatusName(Integer.valueOf(tradeStatus)));
                return Boolean.FALSE;
            } else if ("5".equals(tradeStatus) && "1500".equals(HolidayCopy.getHHmmss().substring(8, 12))) {
                //
                return Boolean.TRUE;
            }
            //
            if (null == redisUtil.get(HolidayCopy.getRealToday() + key)) {
                redisUtil.set(HolidayCopy.getRealToday() + key, tradeStatus);
            }
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 获取东方财富的交易时间
     * @return
     */
    public String getTradeSattus() {
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        ZhangTingBan zhangTingBan = new ZhangTingBan();
        zhangTingBan.setMinutes(HolidayCopy.getHHmmss().substring(8, 12));
        String htmlForStock = ZhangTingBanTaskService.getHtmlStrByUrl("http://push2.eastmoney.com/api/qt/stock/get?fields=f292&secid=1.000001", httpClient, QueryZhangDieTingTask.USER_AGENT);
        return JsonPath.read(htmlForStock, "$.data.f292").toString();
    }

    public String getTradeStatusName(int statusName) {
        String codeName = "";
        switch (statusName) {
            case 1:
                codeName = "开盘竞价";
                break;
            case 2:
                codeName = "交易中";
                break;
            case 3:
                codeName = "盘中休市";
                break;
            case 4:
                codeName = "收盘竞价";
                break;
            case 5:
                codeName = "已收盘";
                break;
            case 6:
                codeName = "停牌";
                break;
            case 7:
                codeName = "退市";
                break;
            case 8:
                codeName = "暂停上市";
                break;
            case 9:
                codeName = "未上市";
                break;
            case 10:
                codeName = "未开盘";
                break;
            case 11:
                codeName = "盘前";
                break;
            case 12:
                codeName = "盘后";
                break;
            case 13:
                codeName = "休市";
                break;
            case 14:
                codeName = "盘中停牌";
                break;
            case 15:
                codeName = "非交易代码";
                break;
            case 16:
                codeName = "波动性中断";
                break;
            case 17:
                codeName = "盘后交易启动";
                break;
            case 18:
                codeName = "盘后集中撮合交易";
                break;
            case 19:
                codeName = "盘后固定价格交易";
                break;
        }
        return codeName;

    }

    public Boolean isWork() {
        if (!isWorkDayTradeTime()) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * h获取日期-当日代表最新的交易日
     * @return
     */
    public String getDayByNum(int day) {
        if(DateUtils.JudgeTime("00:00:00", "09:29:00") ){
            day=day+1;
        }else{
            day=day+0;
        }
        String date = HolidayCopy.getRealToday();
        if(day==0) {
            if (isWorkDay(date)) {
                return date;
            } else {
                for (int i = 1; i < 20; i++) {
                    String newDate = getDateBefore(new Date(), i);
                    if (isWorkDay(newDate)) {
                        return newDate;
                    }
                }
            }
        }else{
            String dateByDay = getDateBefore(new Date(), day);
            if (isWorkDay(dateByDay)) {
                return dateByDay;
            }else {
                int dayNum=0;
                for (int i = 1; i < 20; i++) {
                    String newDate = getDateBefore(new Date(), i);
                    if (isWorkDay(newDate)) {
                        dayNum++;
                        if(dayNum==day){
                            return newDate;
                        }
                    }
                }
            }
        }
        return null;
    }

    public String getDayByNumNotLimit(int day) {
        String date = HolidayCopy.getRealToday();
        if(day==0) {
            if (isWorkDay(date)) {
                return date;
            } else {
                for (int i = 1; i < 20; i++) {
                    String newDate = getDateBefore(new Date(), i);
                    if (isWorkDay(newDate)) {
                        return newDate;
                    }
                }
            }
        }else{
            String dateByDay = getDateBefore(new Date(), day);
            if (isWorkDay(dateByDay)) {
                return dateByDay;
            }else {
                int dayNum=0;
                for (int i = 1; i < 20; i++) {
                    String newDate = getDateBefore(new Date(), i);
                    if (isWorkDay(newDate)) {
                        dayNum++;
                        if(dayNum==day){
                            return newDate;
                        }
                    }
                }
            }
        }
        return null;
    }


    /**
     * h获取日期-当日代表最新的交易日
     * @return
     */
    public String getDayByNum精研(int day) {
        if(DateUtils.JudgeTime("00:00:00", "17:30:00") ){
            day=day+1;
        }else{
            day=day+0;
        }
        String date = HolidayCopy.getRealToday();
        if(day==0) {
            if (isWorkDay(date)) {
                return date;
            } else {
                for (int i = 1; i < 20; i++) {
                    String newDate = getDateBefore(new Date(), i);
                    if (isWorkDay(newDate)) {
                        return newDate;
                    }
                }
            }
        }else{
            String dateByDay = getDateBefore(new Date(), day);
            if (isWorkDay(dateByDay)) {
                return dateByDay;
            }else {
                int dayNum=0;
                for (int i = 1; i < 20; i++) {
                    String newDate = getDateBefore(new Date(), i);
                    if (isWorkDay(newDate)) {
                        dayNum++;
                        if(dayNum==day){
                            return newDate;
                        }
                    }
                }
            }
        }
        return null;
    }






    /**
     * 得到几天前的时间
     * 
     * @param d
     * @param day
     * @return
     */
    public String getDateBefore(Date d, int day) {
        Calendar no = Calendar.getInstance();
        no.setTime(d);
        no.set(Calendar.DATE, no.get(Calendar.DATE) - day);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(no.getTime());
    }

    /**
     * 得到几天前的时间
     * 
     * @param d
     * @param  @returnday
     *      *
     */
    public  String getDateMinutes(String d, int minutes) throws ParseException {
        SimpleDateFormat sdfa = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date= sdfa.parse(d);
        Calendar no = Calendar.getInstance();
        no.setTime(date);
        no.set(Calendar.MINUTE, no.get(Calendar.MINUTE) -minutes);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(no.getTime());
    }

    /**
     * 获取系统最后一个交易日
     * @return
     */
    public String getToday(){
       List<String> dates= companyStockMinutesMapper.queryDates();
      return dates.get(dates.size()-1);
    }

}
